import { fetchRefreshToken, fetchRefreshTokenYellow } from "@/services/auth";
import {
  fetchLogout,
  fetchLogoutYellow,
  fetchUserInfo,
  fetchUserInfoYellow,
} from "@/services/user";
import { useCallback, useEffect, useState } from "react";
import { history, useModel } from "umi";

const { ipcRenderer } = window.require("electron");

export interface IUserToken {
  access_token?: string;
  refresh_token?: string;
}

export interface IUserInfo {
  openID?: string;
  displayName?: string;
  displayNameCn?: string;
  cn?: string;
  headPictureURL?: string;
  email?: string;
}

export default () => {
  const [userToken, setUserToken] = useState<IUserToken>({});
  const [userInfo, setUserInfo] = useState<IUserInfo>({});
  const [isGetUser, setIsGetUser] = useState(false);
  const [isGetToken, setIsGetToken] = useState(false);
  const { setDeviceList } = useModel("device");
  const { EnvMode } = useModel("env");

  useEffect(() => {
    ipcRenderer.on("logout-webRequest", (event: Event, arg: string) => {
      history.push("/");
      setUserInfo({});
      setUserToken({});
      setIsGetUser(false);
      setDeviceList([]);
      ipcRenderer.invoke("saveUserInfo", {});
    });
  }, []);

  const getUserInfo = useCallback(
    (token: string) => {
      if (isGetUser) return;
      if (userInfo.displayName) return;
      setIsGetUser(true);
      if (EnvMode === "YELLOW") {
        fetchRefreshTokenYellow(token)
          .then((res) => {
            if (!res || !res.access_token) return;
            setUserToken({
              access_token: res.access_token,
              refresh_token: res.refresh_token,
            });
            ipcRenderer.invoke("saveUserInfo", {
              access_token: res.access_token,
              refresh_token: res.refresh_token,
            });
            fetchUserInfoYellow(res.access_token).then((res) => {
              if (!res) return;
              if (res.error) {
                console.log(res.error);
              } else {
                setUserInfo(res);
                setIsGetToken(false);
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        fetchRefreshToken(token)
          .then((res) => {
            if (!res || !res.access_token) return;
            setUserToken({
              access_token: res.access_token,
              refresh_token: res.refresh_token,
            });
            ipcRenderer.invoke("saveUserInfo", {
              access_token: res.access_token,
              refresh_token: res.refresh_token,
            });
            fetchUserInfo(res.access_token).then((res) => {
              if (!res) return;
              if (res.error) {
                console.log(res.error);
              } else {
                setUserInfo(res);
                setIsGetToken(false);
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    [userToken, userInfo]
  );

  const logout = useCallback(() => {
    if (EnvMode === "YELLOW") {
      fetchLogoutYellow().then(() => {
        history.push("/");
        setUserInfo({});
        setUserToken({});
        setIsGetUser(false);
        setDeviceList([]);
        ipcRenderer.invoke("saveUserInfo", {});
      });
      return;
    }
    if (!userToken?.refresh_token) {
      history.push("/");
      setDeviceList([]);
      return;
    }
    fetchRefreshToken(userToken.refresh_token)
      .then((res) => {
        if (!res || !res.access_token) return;
        setUserToken({
          access_token: res.access_token,
          refresh_token: res.refresh_token,
        });
        fetchLogout(res.access_token).finally(() => {
          history.push("/");
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }, [userToken]);

  return {
    userToken,
    setUserToken,
    userInfo,
    getUserInfo,
    logout,
    isGetToken,
    setIsGetToken,
    setUserInfo,
  };
};
